package com.hrs.interceptors;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.hrs.common.anno.RequestLimit;
import com.hrs.common.constant.RedisConstants;
import com.hrs.common.exception.GlobalException;
import com.hrs.common.result.CodeMsg;
import com.hrs.common.result.Result;
import com.hrs.third.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 摆渡人
 * @description 请求次数拦截器
 * @date 2022/12/9 21:32
 */
@Slf4j
@Component
public class RequestLimitInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断请求是否属于方法的请求
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            //获取方法中的注解，看是否有该注解
            RequestLimit accessLimit = handlerMethod.getMethodAnnotation(RequestLimit.class);
            if (accessLimit == null) {
                return true;
            }

            int seconds = accessLimit.seconds();//单位时间
            int maxCount = accessLimit.maxCount();//最大次数
            String code = accessLimit.code();
            String ip = request.getLocalAddr();//ip地址

            //从redis中获取用户访问的次数
            String key = RedisConstants.REQUEST_LIMIT  + code + ip;
            Integer count = redisService.getObject(key, Integer.class);

            if (count == null) {
                //第一次访问
                redisService.set(key,1,seconds,TimeUnit.SECONDS);
            } else if(count < maxCount){
                Long expire = redisService.getExpire(key);
                redisService.set(key,count + 1,expire,TimeUnit.SECONDS);
            } else {
                throw new GlobalException(new CodeMsg("请求太频繁了，请稍后再试"));
            }
        }
        return true;
    }

}
